using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;

namespace AuthorizeNET {
	public static class NameValueSerializer {

		static NameValueSerializer() {
			
		}

		public static string Serialize(INameValueSerializable obj) {
			string result = string.Empty;

			List<String> buffer = new List<string>();
			PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);
			string key_name = string.Empty;
			string key_value = string.Empty;
			foreach (PropertyDescriptor desc in properties) {
				key_name = ((KeyNameAttribute)desc.Attributes[typeof(KeyNameAttribute)]).Name;
				key_value = EncodeValue(desc.GetValue(obj));

				if (!String.IsNullOrEmpty(key_value)) buffer.Add(String.Format("{0}={1}", key_name, key_value));
			}

			result = String.Join("&", buffer.ToArray());
			return (result);
		}

		static string EncodeValue(object val) {
			return (HttpUtility.UrlEncode(TranslateValue(val)));
		}

		static string TranslateValue(object val) {
			if (val == null) return (String.Empty);
			else if (val is string) return ((String)val);
			else if (val is char) return (Convert.ToString(val));
			else if (val is bool) return (Convert.ToBoolean(val).ToString().ToUpperInvariant());
			else if (val is short) return (Convert.ToInt16(val).ToString());
			else if (val is int) return (Convert.ToInt32(val).ToString());
			else if (val is long) return (Convert.ToInt64(val).ToString());
			else if (val is double) return (Convert.ToDouble(val).ToString("N2"));
			else if (val is DateTime) return (Convert.ToDateTime(val).ToString("MMyyyy"));
			else if (val is Enum) return (GeneralLookup.GetEnumTypeString((Enum)val));
			else return (string.Empty);
		}
	}
}
